import { ThemeConfig } from '../types';

export class ThemeManager {
  private static currentTheme: string = 'light';
  private static themes: Map<string, ThemeConfig> = new Map();

  // 初始化默认主题
  static initialize(): void {
    // 亮色主题
    this.themes.set('light', {
      name: 'light',
      colors: {
        primary: '#2563eb',
        secondary: '#64748b',
        background: '#ffffff',
        surface: '#f8fafc',
        text: '#1f2937',
        textSecondary: '#6b7280',
        border: '#e5e7eb',
        success: '#10b981',
        warning: '#f59e0b',
        error: '#ef4444'
      }
    });

    // 暗色主题
    this.themes.set('dark', {
      name: 'dark',
      colors: {
        primary: '#3b82f6',
        secondary: '#94a3b8',
        background: '#1f2937',
        surface: '#374151',
        text: '#f9fafb',
        textSecondary: '#d1d5db',
        border: '#4b5563',
        success: '#10b981',
        warning: '#f59e0b',
        error: '#ef4444'
      }
    });

    // 从本地存储加载主题偏好
    this.loadThemePreference();
    this.applyTheme(this.currentTheme);
  }

  // 加载主题偏好
  static loadThemePreference(): void {
    const savedTheme = localStorage.getItem('theme');
    if (savedTheme && this.themes.has(savedTheme)) {
      this.currentTheme = savedTheme;
    } else {
      // 默认使用系统偏好
      const prefersDark = window.matchMedia('(prefers-color-scheme: dark)').matches;
      this.currentTheme = prefersDark ? 'dark' : 'light';
    }
  }

  // 保存主题偏好
  static saveThemePreference(): void {
    localStorage.setItem('theme', this.currentTheme);
  }

  // 获取当前主题
  static getCurrentTheme(): string {
    return this.currentTheme;
  }

  // 获取主题配置
  static getThemeConfig(themeName: string): ThemeConfig | undefined {
    return this.themes.get(themeName);
  }

  // 切换主题
  static toggleTheme(): void {
    this.currentTheme = this.currentTheme === 'light' ? 'dark' : 'light';
    this.applyTheme(this.currentTheme);
    this.saveThemePreference();
  }

  // 应用主题
  static applyTheme(themeName: string): void {
    const theme = this.themes.get(themeName);
    if (!theme) return;

    const root = document.documentElement;
    
    // 应用CSS变量
    Object.entries(theme.colors).forEach(([key, value]) => {
      root.style.setProperty(`--${key}-color`, value);
    });

    // 设置数据属性用于CSS选择器
    root.setAttribute('data-theme', themeName);
    
    // 触发主题变化事件
    this.dispatchThemeChangeEvent(themeName);
  }

  // 分发主题变化事件
  private static dispatchThemeChangeEvent(themeName: string): void {
    const event = new CustomEvent('themechange', {
      detail: { theme: themeName }
    });
    window.dispatchEvent(event);
  }

  // 注册新主题
  static registerTheme(themeConfig: ThemeConfig): void {
    this.themes.set(themeConfig.name, themeConfig);
  }

  // 获取所有可用主题
  static getAvailableThemes(): string[] {
    return Array.from(this.themes.keys());
  }

  // 检查是否支持暗色模式
  static supportsDarkMode(): boolean {
    return this.themes.has('dark');
  }

  // 监听系统主题变化
  static watchSystemTheme(): void {
    const mediaQuery = window.matchMedia('(prefers-color-scheme: dark)');
    
    const handler = (e: MediaQueryListEvent) => {
      // 只有在用户没有明确选择主题时才跟随系统
      const userTheme = localStorage.getItem('theme');
      if (!userTheme) {
        this.currentTheme = e.matches ? 'dark' : 'light';
        this.applyTheme(this.currentTheme);
      }
    };

    mediaQuery.addEventListener('change', handler);
  }
}

// 初始化主题管理器
document.addEventListener('DOMContentLoaded', () => {
  ThemeManager.initialize();
  ThemeManager.watchSystemTheme();
});